#!/usr/bin/env python
# -*- coding: utf-8 -*-

import logs, time

from subprocess import Popen, PIPE

from ..lib.plugin import MeliponiniPlugin
from ..lib.config import Config
from ..lib.utils import Utils

config = Config()

def log(s):
    logs.log(s)


class plugin(MeliponiniPlugin):
    def constructor(self, method):
        self.directory = config.get('dirs.www')
        
        if method == 'get':
            self.addHTTPHandler('/www/list/', self.commandList)
            self.addHTTPHandler('/www/backup/', self.commandBackup)
            
        self.addTimer(60, self.timerCheckService)
        
        
    '''
    TIMER checkService
    Comprueba que el servicio Apache esté levantado
    '''
    def timerCheckService(self):
        return

    '''
    GET /www/list/
    '''
    def commandList(self):        
        # respuesta json
        self.responseJSON( Utils.listdirs( self.directory ) )
        
    '''
    GET /www/backup/{dirname}/
    Nos solicitan una copia de seguridad de un directorio del directorio de webs
    '''
    def commandBackup(self):
        # path = /www/backup/dirname/
        dir = self.path.split('/')[3]
        source = self.directory + '/' + dir
        target = dir + '-' + time.strftime("%Y%m%d%H%M%S", time.localtime()) + '.tar.bz2'

        # devolvemos el fichero comprimido
        self.responseFile( Utils().compressdir(source), target, 'application/x-bzip2' )

